import { useAppSelector } from '@/store';
import {
  addCurrentIdAction,
  addUserChannelListAction,
  delUserChannelListAction,
  getChannelListAction,
  getUserChannelListAction,
} from '@/store/action/channel';
import { Popup, Tabs, Toast } from 'antd-mobile';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Icon from '../Icon';
import styles from './index.module.scss';
import { differenceBy } from 'lodash';
import { ChannelType } from '@/store/redurce/channel';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

export default function Channel() {
  const [visible, setVisible] = useState(false);
  const [editVisble, setEditVisble] = useState(false);
  const history = useHistory();
  const { allList, currentId, userList } = useAppSelector(
    (state) => state.channel
  );
  //   计算差值 ，方法1：自己过滤
  //   const restList = allList.filter((rest_item) => {
  //     return userList.findIndex((item) => item.id === rest_item.id) === -1;
  //   });
  //   方法2：lodash`
  const restList = differenceBy(allList, userList, 'id');
  console.log('  ----->  ', restList);

  const handleDelete = (id: number) => {
    if (id === 0) {
      Toast.show({ content: '不可删除' });
      return;
    }
    if (!hasToken()) {
      let list = getLocalChannels();
      if (list.length === 5) {
        Toast.show({ content: '不可删除' });
        return;
      }
      list = list.filter((item) => item.id !== id);
      setLocalChannels(list);
      dispatch({ type: 'channel/delUserList', payload: id });
      Toast.show({ content: '删除成功' });
      return;
    }
    if (userList.length === 5) {
      Toast.show({ content: '不可删除' });
      return;
    }
    dispatch(delUserChannelListAction(id));
    Toast.show({ content: '删除成功' });
  };
  const handleAddChannel = (newChannel: ChannelType) => {
    // 2. 新增关注频道时,判断token
    if (!hasToken()) {
      // 缓存
      setLocalChannels([...getLocalChannels(), newChannel]);
      // redux中
      dispatch({
        type: 'channel/addUserList',
        payload: newChannel,
      });
      // 提示用户
      Toast.show({ content: '设置成功' });
      return;
    }
    dispatch(addUserChannelListAction(newChannel));
    Toast.show({ content: '新增成功' });
  };
  const handleChangeId = (id: string) => {
    console.log('id  ----->  ', id);
    dispatch(addCurrentIdAction(Number(id)));
  };
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getChannelListAction());
    dispatch(getUserChannelListAction());
  }, [dispatch]);
  return (
    <div className={styles.root}>
      <Tabs
        activeKey={String(currentId)}
        className="tabs"
        onChange={handleChangeId}
      >
        {userList.map((item) => {
          return <Tabs.Tab title={item.name} key={item.id}></Tabs.Tab>;
        })}
      </Tabs>
      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup
        visible={visible}
        position="left"
        bodyClassName={styles.channelPopup}
      >
        {/* 顶部栏：带关闭按钮 */}
        <div className="channel-header">
          <Icon
            type="iconbtn_channel_close"
            onClick={() => {
              setVisible(false);
              setEditVisble(!editVisble);
            }}
          />
        </div>

        {/* 频道列表 */}
        <div className="channel-content">
          {/* 当前已选择的频道列表 */}
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span
                className="channel-item-edit"
                onClick={() => {
                  setEditVisble(!editVisble);
                }}
              >
                {editVisble ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userList.map((item) => {
                return (
                  <span className="channel-list-item" key={item.id}>
                    {item.name}
                    {editVisble && (
                      <Icon
                        type="iconbtn_tag_close"
                        onClick={() => handleDelete(item.id)}
                      />
                    )}
                  </span>
                );
              })}
            </div>
          </div>

          {/* 推荐的频道列表 */}
          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {restList.map((item) => {
                return (
                  <span
                    className="channel-list-item"
                    key={item.id}
                    onClick={() => handleAddChannel(item)}
                  >
                    + {item.name}
                  </span>
                );
              })}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
